<template>
    <div
        @keyup.esc="(e)=>{e.stopPropagation()}"
        @keydown.esc="(e)=>{e.stopPropagation()}"
    >
        <codemirror
                ref="theCodeMirror"
                v-model="vModel"
                placeholder="Code goes here..."
                :style="{ height: '300px' }"
                :autofocus="true"
                :indent-with-tab="true"
                :tab-size="2"
                :extensions="extensions"
                @ready="handleReady"
        />
        <br/>
        <!--    theCode :{{code}}-->
        <el-button @click="formatTheCode">format it</el-button>
    </div>
  <!--    @change="console.log('change', $event)"-->
  <!--    @focus="console.log('focus', $event)"-->
  <!--    @blur="console.log('blur', $event)"-->
</template>

<script setup>
import {computed, defineComponent, onMounted, ref, shallowRef,defineModel} from 'vue'
import { Codemirror } from 'vue-codemirror'
import { javascript } from '@codemirror/lang-javascript'
import { html } from '@codemirror/lang-html'
import { oneDark } from '@codemirror/theme-one-dark'
import prettier from 'prettier';
import axios from "axios";
// import formmater from 'codemirror-formatting'

const theCode = ref(``);
let vModel = defineModel();
let cptTheModelValue = computed(()=>{
    if(vModel){
        return vModel;
    }else{
        return theCode;
    }
})
const backEndUrl = "http://localhost:3000";

function formatTheCode(){
    axios.post(backEndUrl + '/youdaoMarking/codeMirror/prettier/format', {theCode:vModel.value}).then(function (response) {

        vModel.value = response.data;
        console.log("format resp:",response);
    }).catch(function (error) {
        console.error(error);
    });
}
// const extensions = [javascript(), oneDark]
const extensions = [html(),javascript(), oneDark]
// console.log("prettier:",prettier);
// console.log("formmater:",formmater);
// const extensions = [javascript()]

// Codemirror EditorView instance ref
const view = shallowRef()
const handleReady = (payload) => {
    view.value = payload.view
}

let theCodeMirror = ref();

// Status is available at all times via Codemirror EditorView
const getCodemirrorStates = () => {
    const state = view.value.state
    const ranges = state.selection.ranges
    const selected = ranges.reduce((r, range) => r + range.to - range.from, 0)
    const cursor = ranges[0].anchor
    const length = state.doc.length
    const lines = state.doc.lines
    // more state info ...
    // return ...
}

onMounted(()=>{
    // console.log("theCodeMirror:,",theCodeMirror)
    // console.log("formmater:,",formmater)
})
</script>